﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Microsoft.ISVApps.Common.Utils;
using System.Xml.Linq;
using System.Linq;
using Microsoft.ISVApps.Common.ViewModels;

namespace Microsoft.ISVApps.MyCompany.ViewModels
{
    public class MenuModel 
    {

        public ObservableCollection<Product> Products { get; set; }
        public ObservableCollection<Feed> Feeds { get; set; }

        private WebClient client = new WebClient();
        private ResourceAdapter<string> Res;

        public MenuModel(bool load=false)
        {
            try
            {
                //HACK Designer trick
                Res = Microsoft.ISVApps.Common.Utils.Extensions.GetDefaultResourceAdapter<string>();
            }
            catch { }
            Products = new ObservableCollection<Product>();
            Feeds = new ObservableCollection<Feed>();
            if (load) LoadModel();
        }

        public void LoadModel()
        {
            (Application.Current.Resources["PRODUCTS_LIST"] as ProductList).Products.ForEach(p => Products.Add(p));
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(Res("NEWS_FEED_URL")));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {            
            try
            {
                XDocument doc = XDocument.Parse(e.Result);
                Feeds.Clear();
                doc.Descendants("item").Select(p => new Feed()
                {
                    FeedDate = DateTime.Parse(p.Descendants("pubDate").First().Value),
                    FeedTitle = p.Descendants("title").First().Value,
                    FeedUrl = p.Descendants("link").First().Value
                }).ToList()
                    .ForEach(p => Feeds.Add(p));
            }
            catch (Exception)
            {
                MessageBox.Show(Res("MSG_FEED_EXCEPTION"), Res("MSG_ERROR_HEADER"), MessageBoxButton.OK);
            }
        }

    }
}
